/**
 * Radio Story Cards - using RFID tags to track physical story cards in an agile/lean environment.
 *
 * See http://www.radiostorycards.com for more information.
 *
 *
 * Copyright (C) 2011, Ted M. Young
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package com.radiostorycards.comm;

import com.radiostorycards.domain.tags.RfidTag;

import java.io.IOException;
import java.util.Scanner;

/**
 * RFID Tag translator for the RedBee(tm) RFID Reader
 *
 * @author Ted Young <tedyoung@gmail.com> @JitterTed
 */
public class RedBeeTranslator extends AbstractRfidReaderTagTranslator {

  @Override
  public boolean isEndOfTag(char inputByte) {
    return inputByte == '>';
  }

  @Override
  public RfidTag rfidStringToTag(String rawRfidInputString) throws IOException {
    Scanner scanner = new Scanner(rawRfidInputString);
    try {
      skipStartOfTagData(scanner);
      byte[] rfidTagBytes = readTagAsBytes(scanner);
      return new RfidTag(rfidTagBytes);
    } catch (Exception e) {
      // if we get an exception, it means the input string was bad during scanning, so we'll just ignore it.
      throw new IOException("Raw input string being parsed: \"" + rawRfidInputString + "\"");
    }
  }

  private void skipStartOfTagData(Scanner scanner) {
    // skip the T:NACK (we get a "NACK" instead of an "ACK" because we don't use the RedBee's
    // internal "valid tag" list, so all tags will be "invalid", and come across with "NACK".
    scanner.next();
  }

  private byte[] readTagAsBytes(Scanner scanner) {
    byte[] tagAsBytes = new byte[BYTES_IN_TAG_ID];
    for (int i = 0; i < BYTES_IN_TAG_ID; i++) {
      tagAsBytes[i] = nextTokenAsUnsignedByte(scanner);
    }
    return tagAsBytes;
  }

  private byte nextTokenAsUnsignedByte(Scanner scanner) {
    String nextToken = scanner.next();
    return stringToUnsignedByte(nextToken);
  }

}
